import requests
import os

class translated_lyrics(object):

    def lyric_spider(self, song_id):
        lyric_url = 'https://music.163.com/api/song/lyric?'
        headers = { 
            'accept':'*/*',
            'accept-encoding':'gzip, deflate, br',
            'accept-language':'zh-CN,zh;q=0.9',
            'content-length':'476',
            'content-type':'application/x-www-form-urlencoded',
            'dnt':'1',
            'origin':'https://music.163.com',
            'user-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'
            }
            
        #参数参考：https://blog.csdn.net/weixin_42742658/article/details/103484096
        data = {
            'id':song_id,
            'lv':'1',
            'kv':'1',
            'tv':'1'
        }      

        response = requests.post(url=lyric_url, data=data, headers=headers).json()
        print(response)


        try:
            lyric = response['lrc']['lyric']
            #print(lyric)
            print(lyric)
            print("lyric获取完成")
        except:
            print(response)
            lyric = '无歌词或者纯音乐'

        try:
            tlyric = response['tlyric']['lyric']
            print(tlyric)
            print("tlyric获取完成")
            if tlyric =='':
                tlyric = '无歌词或者纯音乐，无翻译'
        except:
            print(response)
            tlyric = '无歌词或者纯音乐，无翻译'

        return lyric, tlyric


    def save_lyric(self, lyric, tlyric, song_info):
        if not os.path.exists(f'./{song_info}'):
            os.mkdir(f'./{song_info}')

        with open(f'./{song_info}/{song_info}.lrc', 'w', encoding='utf8') as fp1:
                    fp1.write(lyric)
        with open(f'./{song_info}/{song_info}_translated.lrc', 'w', encoding='utf8') as fp2:
                    fp2.write(tlyric)
        
        print(song_info + '.lrc保存完成！')


    def run_lyric(self, song_id, song_info):
        print('获取歌词中！——————————————————')
        lyric, tlyric = self.lyric_spider(song_id)
        self.save_lyric(lyric, tlyric, song_info)
        print('歌词部分完成——————————————————')
        '/{song_info}'

if __name__ == "__main__":
    song_id = int(input('网易云歌曲id：')) #  1374469372
    song_info = input('歌曲信息')
    wyy = translated_lyrics()
    wyy.run_lyric(song_id, song_info)